import { createRouter, createWebHistory } from "vue-router";


let routes = [
  {
    path: '/',
    name: 'home',
    component: () => import("../views/Home.vue"),
    children: [
      {
        path: 'front',
        name: 'front',
        component: () => import('../views/Front.vue'),
      },
      {
        path: 'details/:orderId',
        name: 'details',
        props: true,
        component: () => import('../views/Details.vue'),
      },
      {
        path: 'goods',
        name: 'goods',
        component: () => import('../views/HomeGoods.vue'),
      },
      {
        path: 'purchase',
        name: 'purchase',
        component: () => import('../views/HomePurchase.vue'),
      },
      {
        path: 'knowledge',
        name: 'knowledge',
        component: () => import('../views/HomeKnowLedge.vue'),
      },
      {
        path: 'purchasedetails/:orderId',
        name: 'purchasedetails',
        props: true,
        component: () => import('../views/PurchaseDetails.vue'),
      },
      {
        path: 'addmessage',
        name: 'addmessage',
        component: () => import('../components/PublishNav.vue'),
        children: [
          {
            path: 'publishgoods',
            name: 'publishgoods',
            component: () => import('../views/PublishGoods.vue'),
            meta: { requiresAuth: true, roles: ['1', '2'] }
          },
        ]
      },
      {
        path: 'knowledegedetail/:knowledgeId',
        name: 'knowledegedetail',
        props: true,
        component: () => import('../views/KnowLedgeDetail.vue'),
      },
      {
        path: 'homeguide',
        name: 'homeguide',
        props: true,
        component: () => import('../views/HomeGuide.vue'),
      },
    ]
  },
  {
    path: '/:catchAll(.*)',
    name: '404',
    component: () => import('../views/404.vue'),
  },
  {
    path: '/register',
    name: 'register',
    component: () => import("../views/Register.vue")
  },
  {
    path: '/login',
    name: 'login',
    component: () => import("../views/Login.vue")
  },
]
// 路由
const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, _from, next) => {
  const userType = localStorage.getItem("userType");
  const isLoggedIn = localStorage.getItem("isLoggedIn")
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login'); // 未登录用户跳转到登录页
  } else if (to.meta.requiresAuth && !((to.meta as any).roles || []).includes(userType)) {
    next('/403'); // 用户角色不符合要求，跳转到403页面或其他页面
  } else {
    next(); // 允许访问该路由
  }
});


// 导出
export default router 